<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <link href="../../component/pear/css/pear.css" rel="stylesheet"/>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <div class="layui-online">
                    <label class="layui-form-label">关键字</label>
                    <div class="layui-input-inline">
                        <input type="text" name="keyWord" placeholder="商品名称" class="layui-input">
                    </div>
                </div>
                <div class="layui-online">
                    <label class="layui-form-label">0库存商品</label>
                    <div class="layui-input-inline">
                        <input type="checkbox" name="isDisplay" lay-skin="switch" lay-text="包含|不包含" lay-filter="faultReveal" />
                    </div>
                </div>
                <div class="layui-online">
                    <button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="message-query">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="pear-btn pear-btn-md">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="layui-card">
    <div class="layui-card-body">
        <table id="table" lay-filter="message-filter"></table>
    </div>
</div>

</body>

<script type="text/html" id="table-toolbar">
<!--    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="importExcel">-->
<!--        <i class="layui-icon">&#xe67c;</i>-->
<!--        上传导入-->
<!--    </button>-->
    <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchReport">
        <i class="layui-icon layui-icon-download-circle"></i>
        导出
    </button>
    <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="checkClear">
        <i class="layui-icon layui-icon-close-fill"></i>
        清空
    </button>

<!--    <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="downloadWord">-->
<!--        <i class="layui-icon layui-icon-file-b"></i>-->
<!--        生成WORD-->
<!--    </button>-->
</script>

<script type="text/html" id="record-toolbar">
    <button class="pear-btn pear-btn-primary pear-btn-sm" lay-event="tradein">
        入
    </button>
    <button class="pear-btn pear-btn-warming pear-btn-sm" lay-event="tradeout">
        出
    </button>
</script>

<script src="../../component/layui/layui.js"></script>
<script src="../../component/pear/pear.js"></script>
<script src="../../component/layui_exts/excel.js"></script>
<script src="../../component/layui_exts/FileSaver.js"></script>
<script src="../../component/layui_exts/wordexport.js"></script>
<script>
    layui.use(['table', 'form', 'common', 'easyAdmin'], function () {
        let easyAdmin = layui.easyAdmin;
        let MODULE_PATH = "message";
        let table = layui.table;
        let form = layui.form;
        let common = layui.common;

        let tempAllData = new Array();// 表格数据缓存
        let tempCheckData = new Array();// 勾选集合

        let loading;

        let cols = [
            {checkbox: true, LAY_CHECKED: false, filter:'test'},
            {
                title: '商品名称',
                field: 'commName',
                align: 'center'
            },
            {
                title: '商品规格',
                field: 'commSpecsName',
                align: 'center'
            },
            {
                title: '照片缩略图',
                field: 'commPicUri',
                align: 'center',
                templet: function (d) {
                    var url = d.commPicUri;
                    return '<div style="width:30px;height:30px;border: 1px solid rgb(200, 200, 200);border-radius: 50%;overflow:hidden;"><img src="' + url + '" style="width:30px;height:30px;cursor: pointer;" lay-event="prevPic" title="点击查看" /></div>';
                }
            },
            {
                title: '商品数量',
                field: 'invSum',
                align: 'center'
            }
        ];

        easyAdmin.httpGet("/api/v1/getAdminRole",function (res) {
            if (res.data === "1") {
                let adminCols =
                    {
                        title: '操作',
                        toolbar: '#record-toolbar',
                        align: 'center'
                    };
                cols.push(adminCols);
            }

            var browserWidth = $(window).width();
            if (browserWidth > 780) {
                let othersCols1 =
                    {
                        title: '库存编号',
                        field: 'invId',
                        align: 'center'
                    };
                let othersCols2 =
                    {
                        title: '商品编号',
                        field: 'commId',
                        align: 'center'
                    };
                let othersCols3 =
                    {
                        title: '商品类别',
                        field: 'commTypeName',
                        align: 'center'
                    };
                cols.splice(1, 0, othersCols1, othersCols2);
                cols.splice(3, 0, othersCols3);
            }

            table.render({
                elem: '#table',
                id: 'table',
                url: '/inv/message',
                title: '库存',
                skin: 'line',
                page: true,
                cols: [ cols ],
                toolbar: '#table-toolbar', // 表格头部工具栏 可定义左上角和右上角工具栏,一般用于左上角配置
                defaultToolbar: [{  // 自由配置头部工具栏右侧的图标按钮
                    title: '刷新',
                    layEvent: 'refresh',
                    icon: 'layui-icon-refresh',
                }, 'filter', 'exports'],
                done: function (res, currPage, count) {
                    tempAllData = res.data;
                    //在缓存中找到invId,然后设置data表格中的选中状态
                    //循环所有数据，找出对应关系，设置checkbox选中状态
                    for(var i=0;i<res.data.length;i++){
                        for(var j=0;j<tempCheckData.length;j++){
                            if(res.data[i].invId==tempCheckData[j]){
                                //这里才是真正的有效勾选
                                res.data[i]["LAY_CHECKED"]='true';
                                //找到对应数据改变勾选样式，呈现出选中效果
                                var index= res.data[i]['LAY_TABLE_INDEX'];
                                $('.layui-table tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                                $('.layui-table tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                            }
                        }
                    }
                    //设置全选checkbox的选中状态，只有改变LAY_CHECKED的值， table.checkStatus才能抓取到选中的状态
                    var checkStatus = table.checkStatus('message-filter');
                    if(checkStatus.isAll){
                        $('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                        $('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                    }
                }
            });
        });

        // easyAdmin.tableRender({
        //     elem: '#table', // 对应table的id
        //     url: '/inv/message',
        //     page: true, // 分页参数可以自定义
        //     cols: cols, // 列表示
        //     skin: 'line', // 表格样式
        //     toolbar: '#table-toolbar', // 表格头部工具栏 可定义左上角和右上角工具栏,一般用于左上角配置
        //     defaultToolbar: [{  // 自由配置头部工具栏右侧的图标按钮
        //         title: '刷新',
        //         layEvent: 'refresh',
        //         icon: 'layui-icon-refresh',
        //     }, 'filter', 'print', 'exports']
        // });

        // 选中行监听（临时存储复选数据，用于列表复选框回显上一页）
        table.on('checkbox(message-filter)', function (obj) {
            if(obj.checked==true){
                if(obj.type=='one'){
                    tempCheckData.push(obj.data.invId);
                }else{
                    for(var i=0;i<tempAllData.length;i++){
                        tempCheckData.push(tempAllData[i].invId);
                    }
                }

                tempCheckData = removeDuplicates(tempCheckData);
            }else{
                if(obj.type=='one'){
                    for(var i=0;i<tempCheckData.length;i++){
                        if(tempCheckData[i]===obj.data.invId){
                            tempCheckData.remove(i);
                        }
                    }
                }else{
                    for(var i=0;i<tempCheckData.length;i++){
                        for(var j=0;j<tempAllData.length;j++){
                            if(tempCheckData[i]===tempAllData[j].invId){
                                tempCheckData.remove(i);
                            }
                        }
                    }
                }
            }
        });

        function removeDuplicates(arr) {
            return [...new Set(arr)];
        }

        //删除数组自定义函数
        Array.prototype.remove=function(dx)
        {
            if(isNaN(dx)||dx>this.length){return false;}
            for(var i=0,n=0;i<this.length;i++)
            {
                if(this[i]!=this[dx])
                {
                    this[n++]=this[i]
                }
            }
            this.length-=1
        }

        // toolbar: '#toolbarDemo'
        // toolbar 点击头部工具栏区域设定了属性为 lay-event="" 的元素时触发(包括左上角和右上角)
        table.on('toolbar(message-filter)', function (obj) {
            switch (obj.event) {
                case 'batchReport':
                    batchReportExcel(obj);
                    break;
                case 'checkClear':
                    checkClearFunc(obj);
                    break;
                // case 'downloadWord':
                //     downloadWordFunc(obj);
                //     break;
                case 'importExcel':
                    importExcel(MODULE_PATH);
                    break;
                case 'refresh':
                    easyAdmin.tableRefresh('table');
                    break;
            }
        });

        table.on('tool(message-filter)', function (obj) {
            switch (obj.event) {
                case 'tradein':
                    tradeinEdit(MODULE_PATH, obj.data.invId)
                    break;
                case 'tradeout':
                    tradeoutEdit(MODULE_PATH, obj.data.invId)
                    break;
                case 'prevPic':
                    prevPicOpen(obj);
                    break;
            }
        });

        /**
         * 导出
         */
        let batchReportExcel = function (obj) {
            // // let ids = easyAdmin.checkField(obj, 'invId');
            // // let head = LAY_EXCEL.tableToJson($(".layui-table")[0]);
            // // let body = LAY_EXCEL.tableToJson($(".layui-table")[1]);
            // let head = [];
            // let headLine = [];
            // headLine.push("库存编号");
            // headLine.push("商品编号");
            // headLine.push("商品名称");
            // headLine.push("商品规格");
            // headLine.push("商品类别");
            // headLine.push("商品数量");
            // head.push(headLine);
            // let body = [];
            // let exportData = [];
            // // 获取头部
            // exportData.push.apply(exportData, head);
            layer.load(0, {shade: [0.5, '#393D49']});
            // loading = layer.msg('正在下载', {icon: 16, shade: 0.3, time: 0});

            let keyWordVal = $("input[name='keyWord']").val();
            let isDisplay = $("input[name='isDisplay']:checked").val();
            easyAdmin.http({
                url: '/inv/message/getAll',
                dataType: 'json',
                contentType: 'application/json',
                data: "keyWord=" + keyWordVal + "&isDisplay=" + isDisplay + "&tempCheckData=" + tempCheckData,
                type: 'GET',
                success: function (result) {
                    layer.closeAll('loading');
                    // layer.close(loading);
                    if (result.success) {
                        window.open(result.data, '_blank');
                    //     let allData = result.data;
                    //     if (tempCheckData.length > 0) {
                    //         for (let i = 0; i < allData.length; i++) {
                    //             let line = [];
                    //             let invIdVal = allData[i]['invId'];
                    //             line.push(invIdVal);
                    //             line.push(allData[i]['commId']);
                    //             line.push(allData[i]['commName']);
                    //             line.push(allData[i]['commSpecsName']);
                    //             line.push(allData[i]['commTypeName']);
                    //             line.push(allData[i]['invSum']);
                    //             if ($.inArray(invIdVal, tempCheckData) !== -1) {
                    //                 body.push(line);
                    //             }
                    //         }
                    //     } else {
                    //         for (let i = 0; i < allData.length; i++) {
                    //             let aaa = [];
                    //             aaa.push(allData[i]['invId']);
                    //             aaa.push(allData[i]['commId']);
                    //             aaa.push(allData[i]['commName']);
                    //             aaa.push(allData[i]['commSpecsName']);
                    //             aaa.push(allData[i]['commTypeName']);
                    //             aaa.push(allData[i]['invSum']);
                    //             body.push(aaa);
                    //         }
                    //     }
                    }
                    //
                    // // 获取body
                    // exportData.push.apply(exportData, body)
                    // console.log(exportData)
                    // // 生成文件
                    // LAY_EXCEL.exportExcel(exportData, '商品库存-' + new Date().toLocaleString() + '.xlsx', 'xlsx')
                }
            });
        }

        // 清空
        let checkClearFunc = function (data) {
            let checkStatus = table.checkStatus('message-filter');
            if(checkStatus.isAll){
                $('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', false);
                $('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().removeClass('layui-form-checked');
            }

            for(var i=0;i<tempAllData.length;i++){
                for(var j=0;j<tempCheckData.length;j++){
                    if(tempAllData[i].invId==tempCheckData[j]){
                        //这里才是真正的有效勾选
                        tempAllData[i]["LAY_CHECKED"]='true';
                        //找到对应数据改变勾选样式，呈现出选中效果
                        var index= tempAllData[i]['LAY_TABLE_INDEX'];
                        $('.layui-table tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', false);
                        $('.layui-table tr[data-index=' + index + '] input[type="checkbox"]').next().removeClass('layui-form-checked');
                    }
                }
            }

            tempCheckData = new Array();

            return false;
        }

        // let downloadWordFunc = function (data) {
        //     var content = "Hello world";
        //     var converted = content.replace(/<[^>]*>/g, '');
        //
        //     var tableStr = "<table width='100%' align='center' valign='middle' border='1'><thead><tr><td>序号</td><td>编号</td><td>名称</td></tr></thead><tbody><tr><td>1</td><td>100001</td><td>电脑</td></tr><tr><td>2</td><td>100002</td><td>打印机</td></tr></tbody></table>";
        //
        //     var pageContent = '<html><head><meta charset="utf-8"></head><body>' + tableStr + '</body></html>';
        //
        //     var blob = new Blob(['\ufeff', pageContent], { type: 'application/msword' });
        //
        //     // 导出Word文件
        //     saveAs(blob, 'example.doc');
        // }

        /**
         * 跳转到导入页面
         */
        let importExcel = function (MODULE_PATH) {
            layer.open({
                type: 2,
                title: '导入',
                shade: 0.1,
                area: ['500px', '180px'],
                content: [MODULE_PATH + '/importExcel.html', 'no']
            });
        }

        /**
         * 跳转到消耗页面
         */
        let tradeoutEdit = function (MODULE_PATH, id) {
            layer.open({
                type: 2,
                title: '领用',
                shade: 0.1,
                area: ['500px', '650px'],
                content: [MODULE_PATH + '/out.html?id=' + id, 'no']
            });
        }

        /**
         * 跳转到入库页面
         */
        let tradeinEdit = function (MODULE_PATH, id) {
            layer.open({
                type: 2,
                title: '入库',
                shade: 0.1,
                area: ['500px', '600px'],
                content: [MODULE_PATH + '/in.html?id=' + id, 'no']
            });
        }

        let prevPicOpen = function (obj) {
            var imgSrc = obj.data.commPicUri;
            console.log(imgSrc)
            if (imgSrc != "") {
                // 图片预览
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    area: 'auto',
                    skin: 'layui-layer-nobg', // 没有背景色的class
                    shadeClose: true,
                    content: "<img src='" + imgSrc + "' style='margin: auto; max-width: 100%; : 100%;max-height'>"
                });
            }
        }

        // 触发submit提交 按钮点击或者表单被执行提交时触发
        form.on('submit(message-query)', function (data) {
            table.reload('table', {
                // //设定异步数据接口的额外参数
                where: data.field
            })
            return false; // 阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        form.on('submit(faultReveal)', function (data) {
            table.reload('table', {
                // //设定异步数据接口的额外参数
                where: data.field
            })
            return false; // 阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });
    })
</script>
</html>
